#!/bin/bash

if [[ ! "$_PYAV_ACTIVATED" ]]; then
    export here="$(cd "$(dirname "${BASH_SOURCE[0]}")"; pwd)"
    source "$here/activate.sh"
fi

cd "$PYAV_ROOT"

# Always try to install the Python dependencies they are cheap.
$PYAV_PIP install --upgrade -r tests/requirements.txt


# Skip the rest of the build if it already exists.
if [[ -e "$PYAV_LIBRARY_PREFIX/bin/ffmpeg" ]]; then
    echo "We have a cached build of $PYAV_LIBRARY; skipping re-build."
    exit 0
fi


mkdir -p "$PYAV_LIBRARY_ROOT"
mkdir -p "$PYAV_LIBRARY_PREFIX"
cd "$PYAV_LIBRARY_ROOT"


# Download and expand the source.
if [[ ! -d $PYAV_LIBRARY ]]; then
    url="https://ffmpeg.org/releases/$PYAV_LIBRARY.tar.gz"
    echo Downloading $url
    wget --no-check-certificate "$url" || exit 1
    tar -xzf $PYAV_LIBRARY.tar.gz
    rm $PYAV_LIBRARY.tar.gz
    echo
fi
cd $PYAV_LIBRARY

echo ./configure
./configure \
    --disable-doc \
    --disable-mmx \
    --disable-optimizations \
    --disable-static \
    --disable-stripping \
    --enable-debug=3 \
    --enable-gpl \
    --enable-libx264 \
    --enable-libxml2 \
    --enable-shared \
    --prefix="$PYAV_LIBRARY_PREFIX" \
    || exit 2
echo

echo make
make -j4 || exit 3
echo

echo make install
make install || exit 4
echo

echo Build products:
cd ~
find "$PYAV_LIBRARY_PREFIX" -name '*libav*'
